<template>
  <div id="mapComp" class="mapComp" />
  <input id="pickerInput" type="text" placeholder="输入关键字选取地点">

</template>

<script setup name="mapComp">
import GMap from '@/utils/map/GMap'
import redImg from './assets/red.png'
import qidianImg from './assets/qidian.png'
import zhongdianImg from './assets/zhongdian.png'
import { gcj02towgs84 } from '@/utils/coordinate-util.js'

const emit = defineEmits(['mapEmit'])
let marker = null

GMap.then((AMap) => {
  const map = new AMap.Map('mapComp', {
    zoom: 13,
    center: [118.773319, 31.828123]
  })

  // 添加缩放工具
  const toolbar = new AMap.ToolBar()
  map.addControl(toolbar)

  // 搜索
  AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
    const poiPicker = new PoiPicker({
      input: 'pickerInput'
    })

    poiPicker.on('poiPicked', ({ item }) => {
      const inp = document.getElementById('pickerInput')
      inp.value = item.name
      // map.setCenter(item.location) // 移动到中心位置
      if (marker) map.remove(marker)
      marker = new AMap.Marker({
        title: item.address,
        offset: new AMap.Pixel(-15, -28),
        icon: new AMap.Icon({
          size: new AMap.Size(30, 30), // 图标尺寸
          image: zhongdianImg, // Icon的图像
          imageSize: new AMap.Size(30, 30) // 根据所设置的大小拉伸或压缩图片
        })
      })

      marker.setMap(map)
      marker.setPosition(item.location)
      map.setCenter(item.location)

      emit('mapEmit', item.location)
    })
  })
  map.on('click', ({ lnglat }) => {
    if (marker) map.remove(marker) // 只取一次maker点
    marker = new AMap.Marker({
      position: new AMap.LngLat(lnglat.lng, lnglat.lat),
      offset: new AMap.Pixel(-15, -28),
      icon: new AMap.Icon({
        size: new AMap.Size(30, 30), // 图标尺寸
        image: zhongdianImg, // Icon的图像
        imageSize: new AMap.Size(30, 30) // 根据所设置的大小拉伸或压缩图片
      })

    })
    map.add(marker)
    // gcj02转wgs84坐标
    const coord = gcj02towgs84(parseFloat(lnglat.lng), parseFloat(lnglat.lat))
    lnglat.lng = coord.longitude
    lnglat.lat = coord.latitude
    emit('mapEmit', lnglat)
  })
}).catch(e => console.log(e))

</script>

<style lang="scss" scoped>
.mapComp {
  width: 100%;
  // height: calc(600px - 110px);
  height: 270px;
}

#pickerInput {
  position: absolute;
  z-index: 999;
  top: 20px;
  left: 60px;
  width: 200px;
  padding: 5px 5px;
}

// .amap_lib_placeSearch .poibox.highlight {
//   background-color: #CAE1FF;
// }

// .amap_lib_placeSearch .poi-more {
//   display: none !important;
// }
</style>
